import {
	ref
} from "vue";
import {
	onLoad
} from "@dcloudio/uni-app"

import {
	useUserApis
} from "../../request/user.api";
import {
	showErrorToast,
	showSuccessToast
} from "../../utils/toast.utils";

export const useController = () => {
	const userApis = useUserApis();

	// 搜索内容
	const searchContent = ref("");
	// 选中的用户
	const selectedUser = ref(null);
	// 添加用户表单
	const formData = ref({
		userName: "",
		mobile: ""
	});
	// 未过滤的用户列表
	const userList = ref([
		// {
		// 	id: 1,
		// 	name: "张三",
		// 	mobile: "132****1234",
		// 	isDisable:false,
		// 	selected: false
		// },
	]);

	// 搜索过滤后的用户列表
	const filteredUserList = ref([]);

	onLoad(() => {
		getUserList();
	});

	function search() {
		console.log('searchContent', searchContent.value);
		const keyWords = searchContent.value.trim();
		filteredUserList.value = userList.value.filter((e) => e.mobile.includes(keyWords));
	}

	function clearSearch() {
		searchContent.value = '';
		filteredUserList.value = userList.value;
	}

	function checkSelected() {
		if (!selectedUser.value) {
			showErrorToast("未选择用户");
			throw new Error("未选择用户");
		}
	}

	function clearSelected() {
		selectedUser.value = null;
		filteredUserList.value = filteredUserList.value.map((e) => {
			e.selected = false;
			return e;
		});
	}

	async function getUserList() {
		const data = await userApis.list();
		let list = data.users;
		console.log("list", list);
		list = list.map(e => ({
			...e,
			selected: false
		}));

		userList.value = list;
		filteredUserList.value = list;
	}

	async function createUser() {
		const {
			userName,
			mobile
		} = formData.value;

		await userApis.register({
			name: userName,
			mobile
		});

		formData.value.userName = "";
		formData.value.mobile = "";

		getUserList();
	}

	async function resetPassword() {
		checkSelected();

		await userApis.resetPassword(selectedUser.value.id);
		clearSelected();
	}

	async function deleteUser() {
		checkSelected();

		await userApis.delete(selectedUser.value.id);
		clearSelected();
		getUserList();
	}

	async function switchUserStatus() {
		checkSelected();

		const {
			id,
			isDisable
		} = selectedUser.value;

		await userApis.updateStatus({
			userId: selectedUser.value.id,
			isDisable: !isDisable
		});
		clearSelected();
		getUserList();

	}

	return {
		formData,
		searchContent,
		selectedUser,
		userList,
		filteredUserList,

		checkSelected,
		search,
		clearSearch,
		getUserList,
		createUser,
		resetPassword,
		deleteUser,
		switchUserStatus,
	}
}